package com.ttbj.websocket.interceptor;

import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;

/**
 * WebSocket拦截器----握手之前将登陆用户信息从session设置到WebSocketSession
 * @author Medivh
 */
public abstract class DefultWebSocketHandlerInterceptor extends HttpSessionHandshakeInterceptor {
	private static final Logger logger = LoggerFactory.getLogger(DefultWebSocketHandlerInterceptor.class);
	private String userType;
	 
	public DefultWebSocketHandlerInterceptor(String userType) {
		 this.userType = userType;
	}
	
	/**
	 * 握手前方法
	 * 1.检验用户是否合法
	 * 2.业务的其他处理
	 */
	abstract void beforeHandshake (String userId);
	
	@Override
	public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler,
			Map<String, Object> attributes) throws Exception {
			logger.info("握手前方法调用");
		if (request instanceof ServletServerHttpRequest) {
			ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) request;
			HttpServletRequest httpServletRequest = servletRequest.getServletRequest();
			String userId = httpServletRequest.getParameter(userType);
			logger.info("传递的userNum:{}",userId);
			logger.info("用户类型 :{}",userType);
			attributes.put(userType, userId);
			beforeHandshake(userId);
		}
		return super.beforeHandshake(request, response, wsHandler, attributes);
	}

	@Override
	public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler,
			Exception ex) {
		super.afterHandshake(request, response, wsHandler, ex);
	}

}
